import '../util/_base_export.dart';

class CartBloc with ChangeNotifier {
  List _items = [];
  List get items => _items;

  int _amount = 0;
  int get amount => _amount;

  double _subtotal = 0.0;
  double get subtotal => _subtotal;

  Map _ticket = {};
  Map get ticket => _ticket;
  Map _attach_order = {};
  Map get attach_order => _attach_order;

  void loadStorage() async {
    String? lv_item_str = AppSession.prefs.getString('cart_items');
    if ((lv_item_str ?? '').isNotEmpty) {
      _items = json.decode(lv_item_str.toString());
      updateAmount();
      notifyListeners();
    }
  }

  void clear() {
    _items = [];
    _ticket = {};
    _amount = 0;
    _subtotal = 0;
    AppSession.prefs.setString('cart_items', json.encode(_items));
    notifyListeners();
  }

  findItem(iv_sku_id) {
    var lm_item = {};
    lm_item = _items.firstWhere((item) => item['sku_id'] == iv_sku_id,
        orElse: () => {});
    return lm_item.isNotEmpty ? lm_item : {};
  }

  itemAmount(iv_sku_id) {
    var lm_result;
    var lv_amount = 0;
    lm_result = findItem(iv_sku_id);
    if ((lm_result ?? {}).isNotEmpty) {
      lv_amount = lm_result['amount'];
    }
    return lv_amount;
  }

  void updateAmount() {
    int lv_amount = 0;
    double lv_total = 0.0;
    for (var i = 0; i < _items.length; i++) {
      lv_amount = lv_amount + (_items[i]['amount']) as int;
      lv_total =
          lv_total + double.parse(_items[i]['price']) * _items[i]['amount'];
    }
    _amount = lv_amount;
    _subtotal = lv_total;
  }

  void addItem(im_prod) {
    var lm_item = {};

    lm_item = findItem(im_prod['sku_id']);
    if (lm_item.isNotEmpty) {
      var lv_index = _items.indexOf(lm_item);
      _items[lv_index]['amount']++;
    } else {
      lm_item['sku_id'] = im_prod['sku_id'];
      lm_item['name'] = im_prod['sku_name'];
      lm_item['amount'] = 1;
      lm_item['sale_type'] = im_prod['sale_type'];
      lm_item['outstock_info'] = im_prod['outstock_info'];
      lm_item['image_url'] = im_prod['image_url'];
      lm_item['price'] = im_prod['sku_price'];
      lm_item['sku_desc'] = im_prod['sku_desc'];
      lm_item['unit_desc'] = im_prod['unit_desc'];
      lm_item['price_desc'] = '\$ ' +
          im_prod['sku_price'].toString() +
          ' / ' +
          im_prod['unit_desc'];
      _items.add(lm_item);
    }
    updateAmount();
    AppSession.prefs.setString('cart_items', json.encode(_items));
    notifyListeners();
  }

  void reduceItem(iv_sku_id) {
    var lm_item = {};

    lm_item = findItem(iv_sku_id);
    if (lm_item.isNotEmpty) {
      var lv_index = _items.indexOf(lm_item);
      if (_items[lv_index]['amount'] > 1) {
        _items[lv_index]['amount']--;
      } else {
        _items.remove(lm_item);
      }
    } else {
      print('error');
    }
    updateAmount();
    AppSession.prefs.setString('cart_items', json.encode(_items));
    notifyListeners();
  }

  void removeItem(iv_sku_id) {
    var lm_item = {};

    lm_item = findItem(iv_sku_id);
    if (lm_item.isNotEmpty) {
      _items.remove(lm_item);
    } else {
      print('error');
    }
    updateAmount();
    AppSession.prefs.setString('cart_items', json.encode(_items));
    notifyListeners();
  }
//-----------------------------------------//

  findPaymentChannelDescr(iv_channel) {
    var lm_item = {};
    if (_ticket.isNotEmpty)
      lm_item = _ticket['available_payment_channels'].firstWhere(
          (item) => item['channel'] == iv_channel,
          orElse: () => {});
    if (lm_item.isNotEmpty) {
      return lm_item['descr'];
    } else
      return '';
  }

  checkoutInit() async {
    bool lv_result = false;
    Map<String, dynamic> lm_param = {};

    lm_param = {"version": AppConfig.version, "items": _items};
    print(lm_param);
    var lm_ticket = await AppSession.appReq.futureWrapper(
      ApiConst.httpPost,
      ApiServer.prod + ApiUri.order_co_init,
      {},
      lm_param,
      true,
      true,
    );
    if ((lm_ticket ?? {}).isNotEmpty) {
      if (lm_ticket['ev_error'] == 0) {
        _ticket = lm_ticket['ev_result'];
        lv_result = true;

        if ((lm_ticket['ev_result']['text_msgs'] ?? []).isNotEmpty)
          AppPopupService.showAlertSimple(
              'I', '注意', lm_ticket['ev_result']['text_msgs'][0] ?? '');
      } else if ((lm_ticket['ev_message'] ?? '').isNotEmpty) {
        AppPopupService.showAlertSimple('E', '出错啦', lm_ticket['ev_message']);
      }
    }
    return lv_result;
  }

  checkoutUpdate(Map<String, dynamic> im_param) async {
    bool lv_result = false;
    Map<String, dynamic> lm_param = {};

    lm_param = {
      "ticket_id": _ticket['ticket_id'],
    };
    lm_param.addAll(im_param);
    var lm_ticket = await AppSession.appReq.futureWrapper(
      ApiConst.httpPost,
      ApiServer.prod + ApiUri.order_co_update,
      {},
      lm_param,
      true,
      true,
    );

    if ((lm_ticket ?? {}).isNotEmpty) {
      if (lm_ticket['ev_error'] == 0) {
        _ticket = lm_ticket['ev_result'];
        lv_result = true;
        notifyListeners();
        // AppPopupService.showAlertSimple('I', '注意', lm_ticket['ev_message']);
      } else if ((lm_ticket['ev_message'] ?? '').isNotEmpty) {
        AppPopupService.showAlertSimple('E', '出错啦', lm_ticket['ev_message']);
      }
    }

    return lv_result;
  }

  checkoutSubmit() async {
    Map lm_result = {};
    Map<String, dynamic> lm_param = {};

    lm_param = {
      "ticket_id": _ticket['ticket_id'],
    };

    var lm_ticket = await AppSession.appReq.futureWrapper(
      ApiConst.httpPost,
      ApiServer.prod + ApiUri.order_co_submit,
      {},
      lm_param,
      true,
      true,
    );

    if ((lm_ticket ?? {}).isNotEmpty) {
      // if ((lm_ticket['ev_result'] ?? {}).isNotEmpty) lm_result = lm_ticket['ev_result'];
      if (lm_ticket['ev_error'] == 0)
        lm_result = lm_ticket['ev_result'];
      else if ((lm_ticket['ev_message'] ?? '').isNotEmpty) {
        AppPopupService.showAlertSimple('E', '出错啦', lm_ticket['ev_message']);
      }
    }
    return lm_result;
  }

  orderRepay(int iv_oid) async {
    Map lm_result = {};
    Map<String, dynamic> lm_param = {};

    lm_param = {
      "oid": iv_oid,
    };

    var lm_ticket = await AppSession.appReq.futureWrapper(
      ApiConst.httpPost,
      ApiServer.prod + ApiUri.order_repay,
      {},
      lm_param,
      true,
      true,
    );

    if ((lm_ticket ?? {}).isNotEmpty) {
      if ((lm_ticket['ev_result'] ?? {}).isNotEmpty)
        lm_result = lm_ticket['ev_result'];
    }
    return lm_result;
  }
}
